import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';

import { AppSetting } from '../../providers/app.seting';
import { LoginPage } from '../login/login';
import { ChatRoomPage } from '../chat-room/chat-room';
import { Subscription } from 'rxjs';

import { FriendProvider } from './friend.provider';
import { AddFriendPage } from '../add-friend/add-friend';

/**
 * Generated class for the FriendPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-friend',
  templateUrl: 'friend.html',
  providers: [FriendProvider]
})
export class FriendPage {

  friends: any = [];

  user: any;


  constructor(public navCtrl: NavController, public navParams: NavParams, private appSetting: AppSetting, private friendProvider: FriendProvider) {
    this.user = this.appSetting.getUser();

    if (this.user) {
      this.getHttp(this.user);
    } else {
      this.navCtrl.push(LoginPage);
    }
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad FriendPage');

  }

  addNewFriend(){
    this.navCtrl.push(AddFriendPage);
  }

  chatWith(friend) {

    this.navCtrl.push(ChatRoomPage, { nickname: friend });
  }

  // filter
  filter(ev) {
    // set val to the value of the searchbar
    let val = ev.target.value;

    alert(val);
    // if the value is an empty string don't filter the items
    if (val && val.trim() != '') {
      this.friends = this.friends.filter((item) => {
        return (item.toLowerCase().indexOf(val.toLowerCase()) > -1);
      });
    }
  }

  listenEvent: Subscription;
  getHttp(_user) {
    this.friends.length = 0;
    this.friendProvider.get({ userId: _user._id }).subscribe((res: any) => {

      this.friends = res.data[0].friends;
    });
  }

  ionViewWillLeave() {
    if (this.listenEvent) {
      this.listenEvent.unsubscribe();
    }
  }



}
